import React, { useEffect, useState } from "react";
import contract from "../contracts/Crowdfunding";

function ProjectList() {
  const [projects, setProjects] = useState([]);

  useEffect(() => {
    const fetchProjects = async () => {
      const total = await contract.methods.getTotalProjects().call();
      const temp = [];
      for (let i = 1; i <= total; i++) {
        try {
          const p = await contract.methods.getProject(i).call();
          temp.push(p);
        } catch (err) {
          console.log(`获取项目${i}失败：`, err.message);
        }
      }
      setProjects(temp);
    };
    fetchProjects();
  }, []);

  return (
    <div>
      <h2>所有众筹项目</h2>
      {projects.map((p, index) => (
        <div key={index}>
          <h3>{p.title}</h3>
          <p>描述: {p.description}</p>
          <p>目标金额: {window.web3.utils.fromWei(p.goalAmount)} ETH</p>
          <p>当前金额: {window.web3.utils.fromWei(p.currentAmount)} ETH</p>
        </div>
      ))}
    </div>
  );
}

export default ProjectList;
